﻿// 2020/7/1: 首个版本
// 2021/7/7: 新增freespaceSampleProtocols
// 2023/10/10: 补充部分英文注释
// 2025/4/30: 添加注释

function FreespaceSequencePoints() {
    this.points = []; // [m] List of BIPoint for each sequence / 点(BIPoint)的列表
};

function FreespaceSample(session, time) {
    this.session = session; // Date or AppoxSessionIdentifier
    this.time = time; // [s] Time offset in session / Session内的相对时间
    this.sequences = []; // List of FreespaceSequencePoints (Freespace can be described in multiple sequences) / 可行驶区域序列(FreespaceSequencePoints)的列表，可多段描述
}

function convFreespaceSampleV1(gs) {
    if (gs.values.length < 1) return null;

    var seqCount = gs.values[0] == null ? 0 : gs.values[0];
    if (gs.values.length < 1 + 2 * seqCount) return null;

    var seqBase = 1;
    var ptBase = seqBase + 2 * seqCount;

    var sample = new FreespaceSample(gs.session, gs.time);
    sample.sequences = Array(seqCount);
    for (var i = 0; i < seqCount; i++) {
        if (gs.values[seqBase + 2 * i] == null || gs.values[seqBase + 2 * i + 1] == null) return null;
        var ptOffset = gs.values[seqBase + 2 * i];
        var ptCount = gs.values[seqBase + 2 * i + 1];
        if (gs.values.length < ptBase + 2 * (ptOffset + ptCount)) return null;

        var seq = new FreespaceSequencePoints();
        seq.points = Array(ptCount);
        for (var n = 0; n < ptCount; n++) {
            seq.points[n] = new BIPoint(gs.values[ptBase + 2 * (ptOffset + n)], gs.values[ptBase + 2 * (ptOffset + n) + 1]);
        }
        sample.sequences[i] = seq;
    }
    
    return sample;
}

// Supported protocols / 可行驶区域样本支持解析的协议
var freespaceSampleProtocols = [
    "freespace-sample-v1",
];

// Use this function to query sample at target time / 获取指定session指定时刻最近的可行驶区域样本
function getFreespaceSample(channel, session, time) {
    var pairV1 = biGetGeneralSamplePair('freespace-sample-v1', channel, session, time, 1);
    if (pairV1 != null) {
        return pairV1.weight1 > pairV1.weight2 ? convFreespaceSampleV1(pairV1.sample1) : convFreespaceSampleV1(pairV1.sample2);
    }
    else return null;
}